<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>IntersectionObserver Example</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    .pad {
      height: 1000px;
      background-color: #f0f0f0;
    }

    #target {
      background: rgb(237, 28, 36);
      height: 200px;
      outline: 100px solid rgba(0, 0, 0, 0.2);
      margin: 50px 0;
    }

    #info {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 2rem;
      color: #333;
    }
  </style>
</head>
<body>
  <div class="pad"></div>
  <div id="target"></div>
  <div class="pad"></div>
  <span id="info">isIntersecting = false</span>

  <script>
    const target = document.getElementById('target');
    const info = document.getElementById('info');

    // 创建 IntersectionObserver 实例
    const observer = new IntersectionObserver((entries) => {
      console.log('entries', entries);
      entries.forEach((entry) => {
        console.log('intersectionRatio:', entry.intersectionRatio);
        console.log('boundingClientRect:', entry.boundingClientRect);
        if (entry.isIntersecting) {
          info.textContent = 'isIntersecting = true';
          info.style.color = 'green';
        } else {
          info.textContent = 'isIntersecting = false';
          info.style.color = 'red';
        }
      });
    }, {
      root: null, // 使用浏览器视口
      rootMargin: "0px", // 不扩展视口范围
      threshold: 1.0 // 目标元素完全进入视口时触发
    });

    // 开始观察目标元素
    observer.observe(target);
  </script>
</body>
</html>
